package com.itheima.youdianda.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.youdianda.common.CustomException;
import com.itheima.youdianda.common.R;
import com.itheima.youdianda.dto.CateDto;
import com.itheima.youdianda.dto.HotArticle;
import com.itheima.youdianda.dto.UserDto;
import com.itheima.youdianda.entity.*;
import com.itheima.youdianda.service.*;
import com.itheima.youdianda.util.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/index")
@Slf4j
public class IndexController {

    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private YddAdvimgService yddAdvimgService;
    @Autowired
    private YddAdvposService yddAdvposService;
    @Autowired
    private YddCateService yddCateService;
    @Autowired
    private YddArticleService yddArticleService;
    @Autowired
    private YddTagService yddTagService;
    @Autowired
    private YddUserService yddUserService;

    @GetMapping("/getConfig")
    public R<Map<String, String>> getConfig() {
        LambdaQueryWrapper<SysConfig> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(SysConfig::getTabValue,"system");
        wrapper.eq(SysConfig::getTab_value, "system");
        List<SysConfig> sysConfigs = sysConfigService.list(wrapper);
        Map<String, String> map = new HashMap<>();
        for (SysConfig sysConfig : sysConfigs) {
//            map.put(sysConfig.getAttrKey(),sysConfig.getAttrValue());
            map.put(sysConfig.getAttr_key(), sysConfig.getAttr_value());
        }
        R<Map<String, String>> mapR = new R<>();
        mapR.setData(map);
        mapR.setErrmsg("");
        mapR.setErrno(0);
        return mapR;
    }

    @PostMapping("/login")
    public ResponseEntity<Result> login(HttpServletRequest request, @RequestBody SysUser sysUser) {
        log.info("11111111111");
        String loginName = sysUser.getLogin_name();
        String password = sysUser.getPassword();
        // 将password进行md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getLogin_name, loginName);
        SysUser user = sysUserService.getOne(wrapper);
        if (user == null) {
            throw new CustomException("不存在当前用户");
        }
        if (!password.equals(user.getPassword())) {
            throw new CustomException("当前用户名或密码错误");
        }
        // 清除密码,密码不返回给前端
//        user.setPassword(null);
        // 生成token;
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("id", user.getId());
        String token = AppJwtUtil.getToken(tokenMap);
        HashMap<String, String> map = new HashMap<>();
        map.put("token", token);
        log.info("用户名:{},密码:{}", sysUser.getLogin_name(), sysUser.getPassword());
        request.getServletContext().setAttribute("userId", user.getId());
        System.out.println(request.getSession().getAttribute("userId"));
        return ResponseEntity.ok(new Result(0, "", map));
    }

    @PostMapping("/profile")
    public R<ProfileInfo> profile(HttpServletRequest request) {
        String token = request.getHeader("x-token");
        log.info("token:{}", token);
        // 创建空的返回值对象
        ProfileInfo profileInfo = new ProfileInfo();
        profileInfo.setBtnList(new String[]{"*"});
        // 获取到sys_menu表中的集合数据
        LambdaQueryWrapper<SysMenu> wrapper = new LambdaQueryWrapper<>();
        // 筛选 1=菜单 (排除2=按钮)的数据
        wrapper.eq(SysMenu::getType, 1);
        List<SysMenu> menus = sysMenuService.list(wrapper);
        profileInfo.setMenuList(menus);
        // 获取sys_dict表中相应数据
        Map<String, Map<String, String>> dictsList = sysDictService.getDictsList();
        profileInfo.setDictsList(dictsList);
        // 获取到用户登录成功存入的id
        String userId = (String) request.getServletContext().getAttribute("userId");
        // 获取userInfo信息
        UserDto userDto = sysUserService.getUserDto(userId);
        profileInfo.setUserInfo(userDto);
        return R.success(profileInfo);
    }

    @GetMapping("/baseInfo")
    public R<BaseInfo> baseInfo() {
        log.info("!!!!!");
        BaseInfo baseInfo = new BaseInfo();
        // 获取admin_num值(user表总数)
        int admin_num = sysUserService.count();
        baseInfo.setAdmin_num(admin_num);
        // 获取advimg_num值
        int advimg_num = yddAdvimgService.count();
        baseInfo.setAdvimg_num(advimg_num);
        // 获取advpos_num值
        int advpos_num = yddAdvposService.count();
        baseInfo.setAdvpos_num(advpos_num);
        // 获取article_num
        int article_num = yddArticleService.count();
        baseInfo.setArticle_num(article_num);
        // 获取cate数据以及此分类下文章的数量
        LambdaQueryWrapper<YddCate> cateWrapper = new LambdaQueryWrapper<>();
        cateWrapper.select(YddCate::getId,YddCate::getCatename);
        // 存储all_cate数据
        List<YddCate> cateList = yddCateService.list(cateWrapper);
        List<CateDto> cateDtoList = new ArrayList<>();
        for (YddCate yddCate : cateList) {
            CateDto cateDto = new CateDto();
//            BeanUtils.copyProperties(yddCate,cateDto);
            Integer cateId = yddCate.getId();
            LambdaQueryWrapper<YddArticle> articleWrapper = new LambdaQueryWrapper<>();
            articleWrapper.eq(YddArticle::getCateid,cateId);
            int num = yddArticleService.count(articleWrapper);
            cateDto.setCatename(yddCate.getCatename());
            cateDto.setId(cateId);
            cateDto.setNum(num);
            cateDtoList.add(cateDto);
        }
        baseInfo.setAll_cate(cateDtoList);

        int cate_num = cateList.size();
        baseInfo.setCate_num(cate_num);;
        // 获取热点数据hot-article
        List<HotArticle> hotArticles = new ArrayList<>();
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddArticle::getIshot, 1);
        List<YddArticle> articleList = yddArticleService.list(wrapper);
        for (YddArticle yddArticle : articleList) {
            HotArticle hotArticle = new HotArticle();
            hotArticle.setId(yddArticle.getId());
            hotArticle.setAuthor(yddArticle.getAuthor());
            hotArticle.setClick(yddArticle.getClick());
            hotArticle.setKeywords(yddArticle.getKeywords());
            hotArticle.setTitle(yddArticle.getTitle());
            hotArticles.add(hotArticle);
        }
        baseInfo.setHot_article(hotArticles);
        // 获取tag_num
        int tag_num = yddTagService.count();
        baseInfo.setTag_num(tag_num);
        // 查询user数据
        Map<String, Integer> userNap = new HashMap<>();
        int userTotal = yddUserService.count();
        userNap.put("total",userTotal);
        LambdaQueryWrapper<YddUser> manWrapper = new LambdaQueryWrapper<>();
        manWrapper.eq(YddUser::getSex,1);
        int man_count = yddUserService.count(manWrapper);
        userNap.put("user_man",man_count);
        LambdaQueryWrapper<YddUser> womanWrapper = new LambdaQueryWrapper<>();
        womanWrapper.eq(YddUser::getSex,0);
        int woman_count = yddUserService.count(womanWrapper);
        userNap.put("user_woman",woman_count);
        baseInfo.setUser(userNap);

        // 查询new_user数据
        LambdaQueryWrapper<YddUser> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.orderByDesc(YddUser::getId);
        userWrapper.last("limit 7");
        userWrapper.select(YddUser::getAddress,YddUser::getIcon,YddUser::getId,YddUser::getSex,YddUser::getUsername);
        List<YddUser> userList = yddUserService.list(userWrapper);
        baseInfo.setNew_user(userList);
        return R.success(baseInfo);
    }
}
